"""
订单模型
"""
from sqlalchemy import Column, String, Integer, Numeric, Enum, ForeignKey, DateTime, func
from sqlalchemy.orm import relationship
from .base import Base


class Order(Base):
    """订单表"""
    __tablename__ = "orders"
    
    order_no = Column(String(50), unique=True, nullable=False, comment="订单号")
    student_id = Column(Integer, ForeignKey("students.id"), nullable=False, comment="学员ID")
    course_id = Column(Integer, ForeignKey("courses.id"), nullable=False, comment="课程ID")
    payment_method = Column(Enum("支付宝", "微信", "银行卡", "现金", "其他", name="payment_method"), 
                           comment="支付方式")
    registration_type = Column(Enum("新报名", "续费", "转班", "其他", name="registration_type"), 
                              default="新报名", comment="报名类型")
    should_pay_amount = Column(Numeric(10, 2), nullable=False, comment="应缴金额")
    actual_pay_amount = Column(Numeric(10, 2), nullable=False, comment="实缴金额")
    order_date = Column(DateTime, nullable=False, comment="订单日期")
    sales_employee_id = Column(Integer, ForeignKey("employees.id"), comment="售前员工ID")
    reception_employee_id = Column(Integer, ForeignKey("employees.id"), comment="接待员工ID")
    customer_service_employee_id = Column(Integer, ForeignKey("employees.id"), comment="客服员工ID")
    performance_source = Column(String(50), comment="业绩来源")
    status = Column(Enum("pending", "paid", "refunded", "cancelled", name="order_status"), 
                   default="pending", comment="订单状态")
    
    # 关系
    student = relationship("Student", back_populates="orders")
    course = relationship("Course", back_populates="orders")
    sales_employee = relationship("Employee", foreign_keys=[sales_employee_id], back_populates="sales_orders")
    reception_employee = relationship("Employee", foreign_keys=[reception_employee_id], back_populates="reception_orders")
    customer_service_employee = relationship("Employee", foreign_keys=[customer_service_employee_id], back_populates="customer_service_orders")
    
    # 课程分配
    course_assignments = relationship("StudentCourseAssignment", back_populates="order")
    
    # 支付和退款
    payment_records = relationship("PaymentRecord", back_populates="order")
    refund_records = relationship("RefundRecord", back_populates="order")
    
    def __repr__(self):
        return f"<Order(id={self.id}, order_no='{self.order_no}', student_id={self.student_id})>"
